package com.woniuxy.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 用户认证
 */
@Slf4j
@Order(1)//值越小优先级越高
@Component
public class LoginFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //从请求头获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");

        //校验token，成功：放行  失败：提示认证失败
        try {
            boolean verify = JWTUtil.verify(token, "woniu".getBytes());
            if(!verify){
                return getVoidMono(exchange);
            }
        } catch (Exception e) {
            log.error("login Filter is error:{}, token:{}", e, token);
            return getVoidMono(exchange);
        }

        //放行
        return chain.filter(exchange);
    }


    private static Mono<Void> getVoidMono(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        String jsonStr = "{\"status\":\"400\", \"msg\":\"token非法\"}";
        byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }
}
